package com.jz.community.basecomm.net.retrofit;

import android.app.Activity;
import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.jz.community.basecomm.bean.BaseResponseInfo;
import com.jz.community.basecomm.utils.JsonFormatUtils;
import com.jz.community.basecomm.utils.LoggerUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.WpToast;
import com.orhanobut.logger.Logger;

import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Tony on 16/3/18.
 */
public class ErrorHandle {
    private Context mContext;

    public ErrorHandle(Context context) {
        this.mContext = context;
    }

    public Response handleResponseError(Response response) {

        String bodyString = "";
        try {
            if (response.isSuccessful()) {
                bodyString = response.body().string();
                Logger.i(JsonFormatUtils.format(bodyString));
                if (!Preconditions.isNullOrEmpty(bodyString)) {
                    return responseBuilder(response, bodyString);
                } else {
                    BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
                    baseResponseInfo.setCode(response.code());
                    return responseBuilder(response, JSON.toJSONString(baseResponseInfo));
                }
            } else {
                bodyString = response.body().string();
                isError(response);
                Logger.e("请求出错，错误代码: " + response.code() + ",请稍后再试");
                Logger.i(JsonFormatUtils.format(bodyString));
                return responseBuilder(response, bodyString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseBuilder(response, bodyString);
    }

    /**
     * Response
     *
     * @param response
     * @param bodyString
     * @return
     */
    private Response responseBuilder(Response response, String bodyString) {
        return response.newBuilder()
                .body(ResponseBody.create(response.body().contentType(), bodyString))
                .build();
    }

    /**
     * 错误码处理
     *
     * @return
     */
    private void isError(Response response) {
        if (response.code() == ApiException.SERVICE_UNAVAILABLE || response.code() == ApiException.INTERNAL_SERVER_ERROR) {
            showToast("服务器异常" + "(" + response.code() + ")");
        }
    }

    public void showToast(final String str) {
        if (mContext instanceof Activity) {
            ((Activity) mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    WpToast.l(mContext, str);
                }
            });
        }
    }
}
